package org.datacoder.util

import org.hibernate.proxy.HibernateProxy
import org.datacoder.*
import org.datacoder.geocoding.jurisdiction.*

class ServiceUtils {
    public static void save(Object obj, boolean flush) {
        if(!obj.save(flush:flush)){
            obj.errors.each{System.err.println(it)}
            throw new DAOException("Object with id ${obj.id} " +
                "failed to save.", obj.errors)
        }
    }
    public static void save(Object obj){
        save(obj, false)
    }

    public static int calculateDifference(Date a, Date b){
        int tempDifference = 0
        int difference = 0
        Calendar earlier = Calendar.getInstance()
        Calendar later = Calendar.getInstance()

        if(a.compareTo(b) < 0){
            earlier.setTime(a)
            later.setTime(b)
        }
        else{
            earlier.setTime(b)
            later.setTime(a)
        }

        while(earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR)){
            tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR))
            difference += tempDifference

            earlier.add(Calendar.DAY_OF_YEAR, tempDifference)
        }

        if(earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR)){
            tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR)
            difference += tempDifference

            earlier.add(Calendar.DAY_OF_YEAR, tempDifference)
        }

        return difference
    }

    public static String replaceSubstring(String string, String newSubstring, int first, int last){
        return string.substring(0, first) + newSubstring + string.substring(last)
    }

    public static Object getRealObject(Object obj) {
        return (obj instanceof HibernateProxy) ?
            ((HibernateProxy) obj).getHibernateLazyInitializer().getImplementation() : obj
    }


    public static Class getRealClass(Object obj) {
        def klasses = [
                CongressionalDistrict,
                Country,
                County,
                Municipality,
                RepresentativeDistrict,
                SenatorialDistrict,
                State,
                ZipCode,

                // Keep this last, since it is a super class
                Jurisdiction,
            ]
        for (k in klasses) {
            if (obj.instanceOf(k)) {
                return k
            }
        }
    }
}
